package com.foruo.modules.demo;


import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

/**
 * 数据库连接工厂类
 * @author GaoYuan
 * @date 2018/5/10 下午3:21
 */
public class ConnectionFactory {

    private static Connection conn = null;
    /** 驱动 */
    private static String driver;
    /** 数据库连接地址 */
    private static String url;
    /** 连接账号 */
    private static String user;
    /** 连接密码 */
    private static String password;

    private static ConnectionFactory connectionFactory = new ConnectionFactory();

    /** 初始化加载连接参数 */
    static {
        Properties prop = new Properties();
        try {
            InputStream in = ConnectionFactory.class.getClassLoader().getResourceAsStream("config.properties");
            prop.load(in);
        } catch (Exception e) {
            System.out.println("properties file read error");
        }

        driver = prop.getProperty("jdbc.driver");
        url = prop.getProperty("jdbc.url");
        user = prop.getProperty("jdbc.username");
        password = prop.getProperty("jdbc.password");
    }

    private ConnectionFactory() {

    }

    public Connection getConnection() {
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static ConnectionFactory getInstance() {
        return connectionFactory;
    }
}